--DelteWorldUI.lua
require 'fairygui.Window'

DelteWorldUI = class(Window)
local prop = property(DelteWorldUI)
prop:accessor("world_id", 0)

function DelteWorldUI:__init()
    self:loadLayout("DelteWorldUI", "Main")
end

function DelteWorldUI:initEvent()
    self:addClick("Confirm", function()
        -- 删除世界
        g_event_mgr:notifyListener("onDelWorld", self.world_id)
        self:close()
    end)
    self:getChild("Cancel").onClick:Add(function()
        self:close()
    end)
end

function DelteWorldUI:SetInfo(id, name)
    self.world_id = id
    local message = self:getChild("message")
    message:SetVar("name", name)
    message:FlushVars()
end

-- 填充切换
function DelteWorldUI:SwitchFill(input)
    local focus = false
    local fillNum = 0
    for i=0,5 do
        local itemInput = self:getChild("inputCode"..i)
        if not focus and itemInput.text == "" then
            itemInput:RequestFocus()
            focus = true
        end
        if itemInput.text == "0" then
            fillNum = fillNum + 1
        end
    end
    self:getChild("Confirm").enabled = fillNum == 6 and true or false;
end

-- 清理切换
function DelteWorldUI:SwitchClear(input)
    local index = tonumber(input.data)
    if index == 0 then
        for i=5,1,-1 do
            local itemInput = self:getChild("inputCode"..i)
            if itemInput.text ~= "" then
                itemInput:RequestFocus()
            break
            end
        end
    else
        for i=index,0,-1 do
            local itemInput = self:getChild("inputCode"..i)
            if itemInput.text ~= "" then
                itemInput:RequestFocus()
            break
            end
        end
    end
    self:getChild("Confirm").enabled = false;
end

-- 打开UI执行一次
function DelteWorldUI:initComponent()
    local controller = self:getController("focused")
    for i=0,5 do
        local input = self:getChild("inputCode"..i)
        input.text = ""
        -- 焦点进入
        input.onFocusIn:Add(function()
            controller.selectedIndex = tonumber(input.data)
        end)
        -- 焦点离开
        input.onFocusOut:Add(function()
            controller.selectedIndex = tonumber(input.data)
        end)
        -- 文本变化
        input.onChanged:Add(function()
            if input.text == "" then
                self:SwitchClear(input)
            else
                self:SwitchFill(input)
            end
        end)
    end
    controller.selectedIndex = 0
    self:getChild("inputCode0"):RequestFocus()
    self:getChild("Confirm").enabled = false;
end